package com.codeman.web.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.codeman.business.user.domain.UserBookshelf;
import com.codeman.business.user.domain.UserDetails;
import com.codeman.business.user.domain.User;
import com.codeman.business.user.mapper.UserBookshelfMapper;
import com.codeman.business.user.service.IUserBookshelfService;
import com.codeman.business.user.service.IUserService;
import com.codeman.common.constant.UserConstants;
import com.codeman.common.core.controller.BaseController;
import com.codeman.common.core.domain.AjaxResult;
import com.codeman.common.core.page.TableDataInfo;
import com.codeman.common.core.redis.RedisCache;
import com.codeman.utils.CookieUtil;
import com.codeman.utils.JwtTokenUtil;
import com.codeman.utils.RandomValidateCodeUtil;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * @author Administrator
 */
@RestController
@RequestMapping("user")
public class UserController extends BaseController {

//    private final CacheService cacheService;
//
@Autowired
private IUserBookshelfService userBookshelfService;
    @Autowired
    private UserBookshelfMapper userBookshelfMapper;
    @Autowired
    private IUserService userService;
    @Autowired
    protected JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisCache redisCache;

    /**
     * 生成验证码
     */
//    @GetMapping(value = "getVerify")
//    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
//        try {
//            //设置相应类型,告诉浏览器输出的内容为图片
//            response.setContentType("image/jpeg");
//            //设置响应头信息，告诉浏览器不要缓存此内容
//            response.setHeader("Pragma", "No-cache");
//            response.setHeader("Cache-Control", "no-cache");
//            response.setDateHeader("Expire", 0);
//            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
//            //输出验证码图片方法
//            randomValidateCode.getRandcode(redisCache, response);
//        } catch (Exception e) {
//            logger.error("获取验证码失败>>>> ", e);
//        }
//    }
    /**
     * 登陆
     */
    @PostMapping("login")
    public AjaxResult login(@RequestBody User user) {
        logger.info(user.toString());
        //登陆
        UserDetails userDetails = userService.login(user);

        Map<String, Object> data = new HashMap<>(1);
        data.put("token", jwtTokenUtil.generateToken(userDetails));

        return AjaxResult.success(data);


    }

    /**
     * 注册
     */
    @PostMapping("register")
    public AjaxResult register(@RequestBody  User user) {
        logger.info(user.toString());
        //注册
        UserDetails userDetails = userService.register(user);
        logger.info(userDetails.toString());
        Map<String, Object> data = new HashMap<>(1);
        data.put("token", jwtTokenUtil.generateToken(userDetails));

        return AjaxResult.success(data);


    }


    /**
     * 刷新token
     */
    @PostMapping("refreshToken")
    public AjaxResult refreshToken(HttpServletRequest request) {
        String token = getToken(request);
        if (jwtTokenUtil.canRefresh(token)) {
            token = jwtTokenUtil.refreshToken(token);
            Map<String, Object> data = new HashMap<>(2);
            data.put("token", token);
            UserDetails userDetail = jwtTokenUtil.getUserDetailsFromToken(token);
            data.put("username", userDetail.getUsername());
            data.put("nickName", userDetail.getNickName());
            return AjaxResult.success(data);

        } else {
            return AjaxResult.error(UserConstants.NO_LOGIN);
        }

    }

//    /**
//     * 查询小说是否已加入书架
//     */
//    @GetMapping("queryIsInShelf")
//    public AjaxResult queryIsInShelf(Long bookId, HttpServletRequest request) {
//        UserDetails userDetails = getUserDetails(request);
//        if (userDetails == null) {
//            return AjaxResult.error(UserConstants.NO_LOGIN);
//        }
//        return ResultBean.ok(userService.queryIsInShelf(userDetails.getId(), bookId));
//    }

    /**
     * 加入书架
     * */
    @PostMapping("addToBookShelf")
    public AjaxResult addToBookShelf(@RequestBody UserBookshelf userBookshelf , HttpServletRequest request) {
        UserDetails userDetails = getUserDetails(request);
        if (userDetails == null) {
            return AjaxResult.error(UserConstants.NO_LOGIN);
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",userDetails.getId());
        queryWrapper .eq("book_id",userBookshelf.getBookId());
        queryWrapper.eq("pre_content_id",userBookshelf.getPreContentId());
        userBookshelf.setUserId(userDetails.getId());
        userBookshelfService.saveOrUpdate(userBookshelf,queryWrapper);
        return AjaxResult.success();
    }

    /**
     * 移出书架
     * */
    @DeleteMapping("removeFromBookShelf/{bookId}")
    public AjaxResult removeFromBookShelf(@PathVariable("bookId") Long bookId, HttpServletRequest request) {
        UserDetails userDetails = getUserDetails(request);
        if (userDetails == null) {
            return AjaxResult.error(UserConstants.NO_LOGIN);
        }
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("user_id",userDetails.getId());
        queryWrapper .eq("book_id",bookId);

        userBookshelfService.remove(queryWrapper);
        return AjaxResult.success();
    }

    /**
     * 查询书架
     * */
    @GetMapping("listBookShelf")
    public TableDataInfo listBookShelf(HttpServletRequest request) {
        UserDetails userDetails = getUserDetails(request);
        if (userDetails == null) {
            return getDataTableFailed(UserConstants.NO_LOGIN);
        }
        return getDataTable(userBookshelfMapper.getList(userDetails.getId()));
    }

//    /**
//     * 分页查询阅读记录
//     * */
//    @GetMapping("listReadHistoryByPage")
//    public ResultBean listReadHistoryByPage(@RequestParam(value = "curr", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "10") int pageSize,HttpServletRequest request) {
//        UserDetails userDetails = getUserDetails(request);
//        if (userDetails == null) {
//            return ResultBean.fail(ResponseStatus.NO_LOGIN);
//        }
//        return ResultBean.ok(new PageInfo<>(userService.listReadHistoryByPage(userDetails.getId(),page,pageSize)));
//    }
//
//    /**
//     * 添加阅读记录
//     * */
//    @PostMapping("addReadHistory")
//    public ResultBean addReadHistory(Long bookId,Long preContentId, HttpServletRequest request) {
//        UserDetails userDetails = getUserDetails(request);
//        if (userDetails == null) {
//            return ResultBean.fail(ResponseStatus.NO_LOGIN);
//        }
//        userService.addReadHistory(userDetails.getId(),bookId,preContentId);
//        return ResultBean.ok();
//    }
//
//    /**
//     * 添加反馈
//     * */
//    @PostMapping("addFeedBack")
//    public ResultBean addFeedBack(String content, HttpServletRequest request) {
//        UserDetails userDetails = getUserDetails(request);
//        if (userDetails == null) {
//            return ResultBean.fail(ResponseStatus.NO_LOGIN);
//        }
//        userService.addFeedBack(userDetails.getId(),content);
//        return ResultBean.ok();
//    }
//
//    /**
//     * 分页查询我的反馈列表
//     * */
//    @GetMapping("listUserFeedBackByPage")
//    public ResultBean listUserFeedBackByPage(@RequestParam(value = "curr", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "5") int pageSize, HttpServletRequest request){
//        UserDetails userDetails = getUserDetails(request);
//        if (userDetails == null) {
//            return ResultBean.fail(ResponseStatus.NO_LOGIN);
//        }
//        return ResultBean.ok(new PageInfo<>(userService.listUserFeedBackByPage(userDetails.getId(),page,pageSize)));
//    }
//
//    /**
//     * 查询个人信息
//     * */
//    @GetMapping("userInfo")
//    public ResultBean userInfo(HttpServletRequest request) {
//        UserDetails userDetails = getUserDetails(request);
//        if (userDetails == null) {
//            return ResultBean.fail(ResponseStatus.NO_LOGIN);
//        }
//        return ResultBean.ok(userService.userInfo(userDetails.getId()));
//    }
//
//    /**
//     * 更新个人信息
//     * */
//    @PostMapping("updateUserInfo")
//    public ResultBean updateUserInfo(@Validated({UpdateGroup.class}) User user, HttpServletRequest request) {
//        UserDetails userDetails = getUserDetails(request);
//        if (userDetails == null) {
//            return ResultBean.fail(ResponseStatus.NO_LOGIN);
//        }
//        userService.updateUserInfo(userDetails.getId(),user);
//        if(user.getNickName() != null){
//            userDetails.setNickName(user.getNickName());
//            Map<String, Object> data = new HashMap<>(1);
//            data.put("token", jwtTokenUtil.generateToken(userDetails));
//            return ResultBean.ok(data);
//        }
//        return ResultBean.ok();
//    }
//
//
//    /**
//     * 更新密码
//     * */
//    @PostMapping("updatePassword")
//    public ResultBean updatePassword(String oldPassword,String newPassword1,String newPassword2,HttpServletRequest request) {
//        UserDetails userDetails = getUserDetails(request);
//        if (userDetails == null) {
//            return ResultBean.fail(ResponseStatus.NO_LOGIN);
//        }
//        if(!(StringUtils.isNotBlank(newPassword1) && newPassword1.equals(newPassword2))){
//            ResultBean.fail(ResponseStatus.TWO_PASSWORD_DIFF);
//        }
//        userService.updatePassword(userDetails.getId(),oldPassword,newPassword1);
//        return ResultBean.ok();
//    }
//
//    /**
//     * 分页查询用户书评
//     * */
//    @GetMapping("listCommentByPage")
//    public ResultBean listCommentByPage(@RequestParam(value = "curr", defaultValue = "1") int page, @RequestParam(value = "limit", defaultValue = "5") int pageSize,HttpServletRequest request) {
//        UserDetails userDetails = getUserDetails(request);
//        if (userDetails == null) {
//            return ResultBean.fail(ResponseStatus.NO_LOGIN);
//        }
//        return ResultBean.ok(new PageInfo<>(bookService.listCommentByPage(userDetails.getId(),null,page,pageSize)));
//    }
//
//
//    /**
//     * 购买小说章节
//     * */
//    @PostMapping("buyBookIndex")
//    public ResultBean buyBookIndex(UserBuyRecord buyRecord, HttpServletRequest request) {
//        UserDetails userDetails = getUserDetails(request);
//        if (userDetails == null) {
//            return ResultBean.fail(ResponseStatus.NO_LOGIN);
//        }
//        buyRecord.setBuyAmount(bookService.queryBookIndex(buyRecord.getBookIndexId()).getBookPrice());
//        userService.buyBookIndex(userDetails.getId(),buyRecord);
//        return ResultBean.ok();
//    }

    private UserDetails getUserDetails(HttpServletRequest request) {
        String token = getToken(request);
        if(StringUtils.isBlank(token)){
            return null;
        }else{
            return jwtTokenUtil.getUserDetailsFromToken(token);
        }
    }


    protected String getToken(HttpServletRequest request){
        String token = CookieUtil.getCookie(request,"Authorization");
        if(token != null){
            return token;
        }
        return request.getHeader("Authorization");
    }



}
